import router from './index.js'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'


router.beforeEach((to, from, next) =>{
  NProgress.start()
  let token = localStorage.getItem('Authorization');
  const filterPath = ['/login', '/register']
  if(token) {
    if(to.path === '/login') {
      next('/')
    }else {
      if(store.getters.avatar.length === 0){
        store.dispatch('getAvatar');
      }
      if(store.getters.permission_router.length === 0) {
        store.dispatch('generateRouters').then(resultRouter => {
          router.addRoutes(resultRouter) //动态添加路由表
          next({...to, replace: true}) // 确保addRoutes已完成
        })
      }else {
        next()
      }
    }
  }else {
    if(filterPath.indexOf(to.path) !== -1) {
      next()
    }else {
      next({ path: '/login', query: {redirect: to.path}})
    }
  }
})
router.afterEach(()=> {
  NProgress.done()
})
